import mitt from "mitt";
import { defineStore } from "pinia";
import { user } from "../local";
export type SettingUpdated = Partial<typeof SETTING>;
export const settingHub = mitt<{
    update: SettingUpdated;
}>();

/** 处理不能响应式的对象的仓库，为主要仓库 */
export const SETTING = {
    backgroundImage: null as File | null,
};
export const useSettingStore = defineStore("setting_store", {
    state: () => {
        // ! 这个是备份仓库
        return SETTING;
    },
    getters: {},
    actions: {
        /** 设置属性 */
        setSolidData(data: SettingUpdated) {
            Object.assign(SETTING, data);
            this.saveData();
            this.$patch(data);
            settingHub.emit("update", data);
        },
        /** 获取不是响应式对象的对象 */
        getSolidData(key: keyof typeof SETTING) {
            return SETTING[key];
        },
        getDataURL(key: keyof typeof SETTING) {
            const data = SETTING[key];
            if (data && data instanceof Blob) {
                return URL.createObjectURL(data);
            } else {
                return "";
            }
        },
        /** 从数据库刷新 */
        async refreshData() {
            const settings = await user.getItem<typeof SETTING>("setting");
            if (settings) {
                Object.assign(SETTING, settings);
                this.$patch(settings);
                settingHub.emit("update", settings);
            }
        },
        /** 向数据库保存 */
        saveData() {
            user.setItem("setting", SETTING).then((settings) => {
                Object.assign(SETTING, settings);
                this.$patch(settings);
                settingHub.emit("update", settings);
            });
        },
    },
});
